/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

const { add, multiply } = require("lodash");

const PENDING = 'pending'; // 等待状态
const FULLFILLED = 'fullfilled'; // 成功状态
const REJECTED = 'rejected'; // 失败状态

class MyPromise {
    constructor (executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e);
        }
    }
    status = PENDING; // promise的状态
    value = undefined; // 成功后的值
    reason = undefined; // 失败后的原因
    successCallback = []; // 成功回调
    failCallback = [];

    resolve = value => {
        if (this.status !== PENDING) return; // 如果状态不是等待，组织程序向下执行
        this.status = FULLFILLED; // 将状态改为成功
        this.value = value; // 保存成功后的值

        /* 判断成功回调是否存在，如果存在则调用 */

        while(this.successCallback.length) this.successCallback.shift()();
    }
    reject = reason => {
        if (this.status !== PENDING) return; // 如果状态不是等待，组织程序向下执行
        this.status = REJECTED; // 将状态改为失败
        this.reason = reason; // 保存失败后的原因
        while (this.failCallback.length) { // 判断失败回调是否存在，如果存在则调用
            this.failCallback.shift()()
        }
    }
    then (successCallback, failCallback) {
        successCallback = successCallback ? successCallback : value => value; // 可选参数
        failCallback = failCallback ? failCallback : reason => { throw reason }; // 可选参数
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status === FULLFILLED) { // 判断状态
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value);

                        /* 判断x的值是普通值还是promise对象
                        如果是普通值，直接调用resolve
                        如果是promise对象，查看promise对象返回的结果
                        再根据promise对象返回的结果，决定调用resolve还是reject */

                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason);

                        /* 判断x的值是普通值还是promise对象
                        如果是普通值，直接调用resolve
                        如果是promise对象，查看promise对象返回的结果
                        再根据promise对象返回的结果，决定调用resolve还是reject */

                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e);
                    }
                }, 0);
            } else {

                /* 等待
                将成功回调和失败回调存储起来 */

                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value);
    
                            /* 判断x的值是普通值还是promise对象
                            如果是普通值，直接调用resolve
                            如果是promise对象，查看promise对象返回的结果
                            再根据promise对象返回的结果，决定调用resolve还是reject */
    
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0);
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason);
    
                            /* 判断x的值是普通值还是promise对象
                            如果是普通值，直接调用resolve
                            如果是promise对象，查看promise对象返回的结果
                            再根据promise对象返回的结果，决定调用resolve还是reject */
    
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e);
                        }
                    }, 0);
                });
            }
        });
        return promise2;
    }
    finally (callback) {
        return this.then(value => {
            return MyPromise.resolve(callback()).then(() => value);
        }), reason => {
            return MyPromise.resolve(callback()).then(() => { throw reason })
        }
    }
    catch (failCallback) {
        return this.then(undefined, failCallback)
    }
    static all (array) {
        let result = [];
        let index = 0;
        return new MyPromise((resolve, reject) => {
            function addData(key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    resolve(result);
                }
            }
            for (let i = 0; i < array.length; i++) {
                const element = array[i];
                if (element instanceof MyPromise) {
                    element.then(value => addData(i, value), reason => reject(reason)) // promise对象
                } else {
                    addData(i, array[i]);
                }
            }
        })
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value;
        return new MyPromise(resolve => resolve(value));
    }
}

function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject); // promise对象
    } else {
        resolve(x); // 普通值
    }
}

module.exports = MyPromise;